package code.lucamarrocco.struts2.rest.sample;

import static code.lucamarrocco.rest.Plural.plural;
import static java.util.Arrays.asList;

import java.lang.reflect.Method;
import java.util.Formatter;
import java.util.List;

public class UriOf {
	public static final String uriOf(Object... objects) {
		return new Formatter().format("/%s", uriOf(asList(objects))).toString();
	}

	private static final String uriOf(List<Object> objects, Object object) {
		return new Formatter().format("%s/%s", uriOf(objects), uriOf(object)).toString();
	}

	private static final String uriOf(List<Object> objects) {
		if (objects.size() == 1) return uriOf(objects.get(0));
		return uriOf(objects.subList(0, objects.size() - 1), objects.get(objects.size() - 1));
	}

	private static final String uriOf(Object object) {
		if (object instanceof String) return (String) object;
		if (object instanceof Long) return String.valueOf(object);
		if (object instanceof Integer) return String.valueOf(object);
		if (object instanceof Float) return String.valueOf(object);
		if (object instanceof Double) return String.valueOf(object);

		return new Formatter().format("%s/%s", plural(object.getClass().getSimpleName()), getId(object)).toString();
	}

	private static final String getId(Object object) {
		try {
			Method getId = object.getClass().getMethod("getId", new Class[0]);
			if (getId == null) return "";
			return String.valueOf(getId.invoke(object, new Object[0]));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
